import time
import datetime

from django.template.defaultfilters import slugify

from arcade.util import parse_date

from arcade.models import ArcadeCategory

try:
    import tagging
    HAS_TAGGING = True
except ImportError:
    HAS_TAGGING = False

class MochiAdapter(object):
    def preprocess(self, feed_game):
        """
        Runs before a game is added to the database or checked against
        the database so fields match correctly
        feed_game: a json or rss/atom loaded dict representing a game
        returns: a dictionary mapping the json/rss/atom to model kwargs
        """
        dct = dict(
            tag=feed_game['game_tag'],
            game_categories=','.join(feed_game['categories']),
            control_scheme=feed_game['control_scheme'],
            created=parse_date(feed_game['created']),
            description=feed_game['description'],
            feed_approval_created=parse_date(feed_game['feed_approval_created']),
            height=feed_game['height'],
            instructions=feed_game['instructions'],
            key_mappings=feed_game['key_mappings'],
            name=feed_game['name'],
            rating=feed_game['rating'],
            slug=feed_game['slug'],
            swf_url=feed_game['swf_url'],
            game_tags=','.join([t[:49] for t in feed_game['tags']]),
            thumbnail_url=feed_game['thumbnail_url'],
            updated=datetime.datetime(*time.strptime(feed_game['updated'][:-15], "%Y-%m-%d")[:-2]),
            uuid=feed_game['uuid'],
            width=feed_game['width'],
            featured=feed_game['recommended'],
            author=feed_game['author'],
            author_link=feed_game['author_link'],
        )
        return dct
    
    def postprocess(self, game):
        """
        Takes a Game model object and does any post processing on the game
        game: a game model to be post processed
        returns: the finalized game object
        """
        if HAS_TAGGING:
            game.tags = game.game_tags.lower()
        for category in game.game_categories.split(","):
            try:
                cat = ArcadeCategory.objects.get(name=category)
            except ArcadeCategory.DoesNotExist:
                cat = ArcadeCategory.objects.create(name=category, slug=slugify(category), cat_map=category)
            try:
                game.categories.get(name=cat.name)
            except ArcadeCategory.DoesNotExist:
                game.categories.add(cat)
        game.save()
        
        return game
        